<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\facade\Session;
use app\admin\model\AdminRoleModel;
use app\admin\model\AdminModel;
use app\admin\model\AdminMenuModel;
use think\Validate;

class Index extends Controller
{
    public function initialize()
    {
        $username = Session::get('username');
        if (empty($username)) {
            $this->error('请先登录后访问', url('admin/login/index'));
        }
    }

    //首页桌面
    public function index()
    {
        $admin_model = new AdminModel();
        $admin_role_model = new AdminRoleModel();
        $admin_menu_model = new AdminMenuModel();
        $username = Session::get('username');
        //用户名查询用户所属角色
        $user = $admin_model->field('role_id')->where('username', $username)->find();
        $role_name = $admin_role_model->find($user['role_id']);

        //可用菜单节点
        if ($user['role_id'] == 1) {//超级管理员除外
            $where = ['type' => 1];
        } else {
            $where = [['type', '=', 1], ['status', '=', 1], ['id', 'in', $role_name['auth']]];
        }
        $auto = $admin_menu_model->where($where)->select();
        $auth_tree = $admin_menu_model->getTree($auto);

        return $this->fetch('', [
            'role_name' => $role_name['name'],
            'auth_tree' => $auth_tree
        ]);
    }

    /**
     * 欢迎页
     * @param Request $request
     * @return mixed
     */
    public function welcome(Request $request)
    {
        $admin_model = new AdminModel();
        $username = Session::get('username');
        $user = $admin_model->where('username', $username)->find();
        return $this->fetch('', [
            'user' => $user
        ]);
    }

    /**
     * 个人信息
     */
    public function myInfo(Request $request)
    {
        $admin_model = new AdminModel;
        if ($request->isAjax()) {
            $validate = new Validate([
                'password|密码' => 'length:6,18|token',
                'nickname|姓名' => 'length:0,10',
                'phone|手机号' => 'number|length:11',
                'email|邮箱' => 'email'
            ]);
            if ($validate->check($request->param())) {
                $res = $admin_model->myInfo($request->param());
                if ($res['status'] == 'n') {
                    $res['token'] = $request->token();
                }
                return json($res);
            } else {
                return json(['status' => 'n', 'info' => $validate->getError(), 'token' => $request->token()]);
            }
        }
        //修改需要的数据
        $data = $admin_model->getUserByName(Session::get('username'));
        $admin_role_model = new AdminRoleModel;
        $role = $admin_role_model->getAllRole();
        if (empty($data)) {
            $this->error('用户不存在', url('admin/admin/index'));
        }
        return $this->fetch('', ['data' => $data, 'role' => $role]);
    }
}
